import errCallback from './error-tip'
import { ENVAPI } from './data'

const reg = /(http|https):\/\//

const url = ENVAPI.PROD

const noToken = ['/verification-code/send']
const addHeaderVar = (header: any = {}, path) => {
  let token = uni.getStorageSync('token') || { token: '' }
  let platform = uni.getSystemInfoSync().platform
  return {
    token: token,
    clientType: platform === 'android' ? 'Android' : 'iOS',
    clientVesion: '1.0.0',
    ...header
  }
}

const getUrl = (path: string) => {
  if (!reg.test(url)) {
    return path
  }
  return url + path
}

uni.addInterceptor('request', {
  invoke(args) {
    // request 触发前拼接 url
    const path = args.url
    args.url = getUrl(path)
    args.header = addHeaderVar(args.header, path)
    args.data = args.data
  },
  success(args) {
    // 不在这里拦截 不让没发传递参数给调用者
  },
  fail(err) {
    try {
      const { data = {} } = err || {}
      if (data.code !== 0) {
        errCallback.init(data.code, data)
      }
    } catch (err) {
      uni.showModal({
        title: '温馨提示',
        content: err,
        showCancel: false,
        success: () => {}
      })
    }
  }
  // complete(res) {
  //   console.log('interceptor-complete', res)
  // },
})
